# https://gitee.com/yueyinqiu5990/tj12413601/blob/master/assignment4/script_runner.py
# Modified from https://gitee.com/yueyinqiu5990/tj12413601/blob/master/assignment1/script_runner.py
import glob
import os
import sys


def run_main_scripts(question_path: str, scripts: list[str] = None):
    print(f"Finding main scripts...")
    question_path = os.path.abspath(question_path)
    sys.path.append(question_path)

    if scripts:
        main_paths = [os.path.join(question_path, f"main_{s}.py") for s in scripts]
    else:
        main_paths = glob.glob(os.path.join(question_path, "main*.py"))

    print(f"{len(main_paths)} script(s) found: {main_paths}")
    print()

    for main_path in main_paths:
        file_name = os.path.basename(main_path)
        print(f"===Starting {file_name}==============================")
        with open(main_path, encoding="utf8") as script_file:
            script = script_file.read()
        script_globals = {
            "__name__": "__main__",
            "__file__": main_path,
            "__loader__": globals()["__loader__"]
        }
        exec(script, script_globals)
        print(f"==={file_name} Finished==============================")
        print()
